<template>
    <div class="paperEdit" v-loading="loading">
        <h1>编辑试卷</h1>
        <el-form ref="form" :model="paper" label-width="calc(15% + 10px)">
            <el-form-item label="试卷名称">
                <el-input v-model="paper.title"></el-input>
            </el-form-item>
            <el-form-item label="试卷类型">
                <el-select v-model="paper.type" placeholder="请选择试卷类型">
                    <el-option label="固定试卷" value="regular"></el-option>
                    <el-option label="时段试卷" value="time"></el-option>
                    <el-option label="任务试卷" value="task"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="时段时间" v-show="paper.type != 'regular'">
                <el-date-picker
                    v-model="paper.startTime"
                    type="datetime"
                    placeholder="选择开始时间">
                    </el-date-picker>
                <el-date-picker
                    v-model="paper.endTime"
                    type="datetime"
                    placeholder="选择结束时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="试卷时间">
                <el-select v-model="paper.time" placeholder="请选择试卷类型">
                    <el-option :label="item.label" :value="item.time" v-for="(item, index) in paperTimer" :key="index"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="题目列表">
                <div>
                    <el-button type="primary" @click="dialogVisible = true">添加 <i class="el-icon-plus"></i></el-button>
                    <el-button type="primary" @click="dialogRandom = true">随机出题 <i class="el-icon-eleme"></i></el-button>
                    <el-popconfirm
                    title="确定全部删除吗？"
                    icon="el-icon-info"
                    icon-color="red"
                    @confirm="delAll"
                    >
                        <el-button type="danger" style="margin: 0 10px;" slot="reference">全部删除 <i class="el-icon-delete"></i></el-button>
                    </el-popconfirm>
                    <el-button type="primary" @click="sortLevel">按难度排序 <i class="el-icon-eleme"></i></el-button>
                </div>
                <adminTopicList :list="topicList" :checkbox="true" :handleDetele="handleDetele"/>
            </el-form-item>
            <el-form-item label="是否启用">
                <el-switch v-model="paper.status"></el-switch>
            </el-form-item>
            <el-form-item label="是否展示分数">
                <el-switch v-model="paper.showScore"></el-switch>
            </el-form-item>
            <el-form-item>
                <el-popconfirm
                title="确定保存吗？"
                @confirm="onSubmit"
                >
                    <el-button type="primary" slot="reference">保存</el-button>
                </el-popconfirm>
            </el-form-item>
        </el-form>

        <el-dialog
            title="题目列表"
            :visible.sync="dialogVisible"
            :width="$ispc ? '60%' : '98%'">
                <el-checkbox-group v-model="paper.list">
                    
                    <!-- <Query @change="getTopic" :prop="['ids', 'time', 'title', 'type']"/> -->
                    <adminTopicList :list="topicContentRecords" :handleDetele="handleDetele" :delEdit="true"/>
                    <el-pagination
                    @size-change="i => limit = i"
                    @current-change="i => page = i"
                    :current-page="page"
                    :page-size="limit"
                    background
                    layout="total, prev, pager, next, jumper"
                    :total="topicContent.total">
                    </el-pagination>
                </el-checkbox-group>
                <!-- :page-sizes="limits" -->
                <!-- sizes, -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editTopic">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog
        title="随机数量"
        :visible.sync="dialogRandom"
        width="30%">
            <el-input-number v-model="randomLimit" :min="0" :max="topicContent.total - topicList.length"></el-input-number>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogRandom = false">取 消</el-button>
                <el-button type="primary" @click="randomAddTopic">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import adminTopicList from '@/components/topic/adminTopicList'
    import { getPaperById, editPaper } from '@/api/paper'
    import { getTopicList } from '@/api/topic'
    import { mapState } from 'vuex'
    import Query from '@/components/base/query.vue'
    export default {
        components : {
            adminTopicList,
            Query
        },
        data() {
            return {
                dialogRandom : false,
                randomLimit : 0,
                dialogVisible : false,
                topicList : [],
                topicContent : {
                    records : [],
                    total : 0
                },
                limit : 3,
                page : 1,
                paper : {
                    title : undefined,
                    status : true,
                    list : [],
                    type : undefined,
                    startTime : undefined,
                    endTime : undefined,
                    time : undefined,
                },
                loading : false
            }
        },
        computed : {
            ...mapState(['paperTimer', 'limits']),
            topicContentRecords(){
                return this.topicContent.records.slice((this.page - 1) * this.limit, this.page * this.limit)
            }
        },
        created(){
            this.getTopic()
            if(this.$route.query.id){
                this.getById()
            }
        },
        methods : {
            //按难度排序
            sortLevel(){
                this.editTopic()
                this.topicList.sort((a,b) => a.level - b.level)
                this.paper.list = this.topicList.map(n => n.id)
            },
            //删除全部
            delAll(){
                this.topicList = []
                this.paper.list = []
            },
            //随机出题
            randomAddTopic(){
                if (this.randomLimit == 0) {
                    this.dialogRandom = false
                    return
                }

                let self = this

                this.paper.list.push(...random(this.randomLimit))
                this.editTopic()
                this.dialogRandom = false

                function random(limit, ids = []){
                    if(limit <= 0) return
                    let list = self.paper.list.length
                    ? self.topicContent.records.filter(n => self.paper.list.indexOf(n.id) == -1)
                    : self.topicContent.records
                    let id = list[Math.floor(Math.random() * list.length)].id
                    if (!ids.includes(id)) {
                        ids.push(id)
                    }

                    if (limit == ids.length) {
                        return ids
                    }
                    random(limit, ids)
                    return ids
                }
            },
            getById(){
                this.loading = true
                getPaperById(this.$route.query.id).then(res => {
                    this.loading = false
                    if(res.code == 200){
                        res.data.status = res.data.status == 1
                        res.data.showScore = res.data.showScore == 1
                        res.data.list = res.data.list.split(',').map(n => parseInt(n))
                        this.paper = res.data
                        this.getTopic({}, () => this.editTopic())
                    }
                })
            },

            onSubmit(){
                if (!this.paper.time) {
                    this.$message.error('请选择试卷时间')
                    return
                }
                if (!this.paper.type) {
                    this.$message.error('请选择试卷类型')
                    return
                }
                if (!this.paper.title) {
                    this.$message.error('请输入试卷标题')
                    return
                }

                this.loading = true

                let data = {...this.paper}

                data.status = data.status ? 1 : 0
                data.showScore = data.showScore ? 1 : 0
                data.list = data.list.toString()

                editPaper(data).then(res => {
                    this.loading = false
                    if(res.code == 200){
                        this.$message.success('保存成功')
                        this.$router.back()
                    }
                })
            },
            handleDetele(index, data){
                let i = this.paper.list.indexOf(data.id)
                this.paper.list.splice(i, 1)
                this.editTopic()
            },
            getTopic(query = {}, fn){
                this.loading = true
                query.limit = 100000000
                query.page = 1
                getTopicList(query).then(res => {
                    this.loading = false
                    if(res.code == 200){
                        this.topicContent = res.data
                        fn && fn(res.data)
                    }
                })
            },
            editTopic(){
                this.dialogVisible = false
                this.topicList = this.topicContent.records.filter(n => this.paper.list.indexOf(n.id) != -1)
            }
        }
    }
</script>

<style lang="scss" scoped>
.paperEdit{
    padding: 50px;
    background-color: #fff;
}
</style>